from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from  rest_framework.viewsets import ModelViewSet

from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.serializers.skus import SKUserializer, GoodsCategoryserializer, SPUSpecificationSerializer
from meiduo_admin.serializers.specs import SpecsSerialzier
from meiduo_admin.serializers.user import PageNum


class SKUSview(ModelViewSet):
    queryset = SKU.objects.all()
    pagination_class = PageNum
    serializer_class = SKUserializer
    permission_classes = [IsAdminUser]
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword == '' or keyword is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    @action(methods=['get'],detail=False)
    def categories(self,request):
        data = GoodsCategory.objects.filter(subs__id = None)
        ser = GoodsCategoryserializer(data,many=True)
        # ser = GoodsCategoryserializer(data=data,many=True)
        # ser.is_valid()
        return Response(ser.data)

    def specs(self,request,pk):

        spu = SPU.objects.get(id = pk)
        data = spu.specs.all()
        ser = SPUSpecificationSerializer(data,many = True)

        return Response(ser.data)